<template>
  <div class="interaction-start">
    <div class="container">
      <div class="box-left">
        <div class="section">
          <div class="case-tip">
            <div class="case-tipName">{{allocates.classNames || groups.classNames}}</div>
            <div class="sm-group">
              <el-button type="text" size="mini" icon="el-icon-s-custom">{{cases.resourceGroupName}}</el-button>
              <el-button type="text" size="mini" icon="el-icon-s-custom">人数：{{cases.stuNo}}人</el-button>
              <el-button type="text" size="mini" icon="el-icon-s-grid">{{cases.nodeNum}}个环节</el-button>
            </div>
          </div>
        </div>
        <div class="section" v-if="cases.isGroup==='0'">
          <div class="list-box">
            <ul>
              <li @click="addGroup">创建分组<span class="right-arrow">></span></li>
              <li>
                设置分组人数
                <div class="inter-man">
                  <el-input type="number" placeholder="输入每组人数" v-model="groupStuNum"></el-input>
                  人/组
                </div>
              </li>
              <li @click="autoGroup">自动分组<span class="right-arrow"><i class="el-icon-arrow-right"></i></span></li>
            </ul>
          </div>
        </div>
      </div>
      <div class="box-right">
        <!-- 案例背景 -->
        <template v-if="cases.isGroup === '0'">
          <div v-for="(item, index) in stuGroupList" :key="index">
            <div class="case-tip">{{item.caseGroupName}}</div>
            <div class="group-box" v-for="(it, id) in item.stuGroupList" :key="id">
              <div class="group-tips">
                <div class="group-tip">{{it.caseStuGroupName}}</div>
                <div class="group-tipBox">
                  <el-button type="primary" size="mini" @click="addGroupStu(index, id)">添加成员</el-button>
                  <el-button type="primary" size="mini" @click="editGroup(item, it, index, id)">编辑</el-button>
                  <el-button type="danger" size="mini" @click="deleteGroup(index, id)">删除</el-button>
                </div>
              </div>
              <div class="group-con">
                <div class="group-cont" v-for="(i, d) in it.stuGroup" :key="d">
                  <div class="group-man">
                    <img :src="i.headImgUrl" class="group-logo" alt="">
                    <div class="group-stuName">{{i.stuName}}</div>
                  </div>
                  <div class="group-doBox">
                    <el-button type="text" class="group-btn" size="mini" v-if="i.isHeadman==='1'">组长</el-button>
                    <el-button type="primary" class="group-btn" size="mini" @click="handleSetStu(index, id, d)" v-else>设为组长</el-button>
                    <el-button type="danger" class="group-btn" size="mini" @click="handleDeleteStu(index, id, d)">删除</el-button>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
        <template v-else>
          <div v-for="(item, index) in stuGroupList" :key="index">
            <div class="case-tip">{{item.caseGroupName}}</div>
            <div class="group-box" v-for="(it, id) in item.stuGroupList" :key="id">
              <div class="group-tips">
                <div class="group-tip">{{it.stuGroupName}}</div>
              </div>
              <div class="group-con">
                <div class="group-cont" v-for="(i, d) in it.stuGroupDetailList" :key="d">
                  <div class="group-man">
                    <el-button type="text" class="group-btn" size="mini" v-if="i.isHeadman==='1'">组长</el-button>
                    <div class="group-stuName">{{i.stuName}}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </template>
      </div>
    </div>
    <el-dialog :title="editState ? '编辑分组' : '创建分组'" :close-on-click-modal="false" :destroy-on-close="true" width="600px" :visible.sync="isShowGroupState" :before-close="closeGroupBox">
      <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm" label-width="100px" style="padding: 0 10px;">
        <el-form-item prop="groupName" label="分组名称">
          <el-input placeholder="请输入分组名称" v-model="ruleForm.groupName"></el-input>
        </el-form-item>
        <el-form-item prop="groupId" label="分组角色">
          <el-radio-group v-model="ruleForm.groupId">
            <el-radio :label="item.caseGroupId" v-for="(item, index) in allocates.caseGroupList" :key="index">{{item.caseGroupName}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-button type="primary" class="inter-btn" :disabled="btnDisabled" @click="submitGroup('ruleForm')">保存</el-button>
      </el-form>
    </el-dialog>
    <el-dialog title="选择成员" :close-on-click-modal="false" :destroy-on-close="true" width="600px" :visible.sync="isShowStuState" :before-close="closeStuBox">
      <el-table style="width: 100%;" :data="allStus.filter(item => !item.isCheck)" border @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="40">
        </el-table-column>
        <el-table-column prop="headImgUrl" label="学生头像">
          <template slot-scope="scope">
            <img :src="scope.row.headImgUrl" alt="" style="width: 40px;height: 40px;">
          </template>
        </el-table-column>
        <el-table-column prop="stuName" label="学生名称">
        </el-table-column>
      </el-table>
      <el-button type="primary" class="inter-btn" :disabled="btnDisabled" @click="submitStudent">保存</el-button>
    </el-dialog>
    <el-button type="primary" class="inter-btn" :disabled="btnDisabled" v-if="cases.isGroup === '0'" @click="handleSubmit">准备完成，开始实训</el-button>
  </div>
</template>

<script>
import { trainingInteraction, groupAllocation, groupShow, autoGroup, groupCommit } from '@/api/teacher/manage/trainingInteractionManage'
export default {
  name: 'interactionGroup',
  data () {
    return {
      resourceCaseId: this.$route.query.id,
      cases: {
        nodeNum: '',
        resourceCaseId: '',
        resourceCaseName: '',
        resourceGroupName: '',
        caseRequestCn: '',
        caseRequestEn: '',
        resourceCaseBgList: [],
        finishedFlag: '',
        lessonICaseId: '',
        classNames: '',
        currentCaseNodeName: '',
        isGroup: '',
        stuNo: ''
      },
      allocates: {
        caseGroupCount: '',
        caseGroupList: '',
        classNames: '',
        isGroup: '',
        lessonICaseId: '',
        resourceCaseId: '',
        resourceGroupName: '',
        stuGroupList: '',
        stuNo: ''
      },
      groups: {
        caseGroupCount: '',
        caseGroupList: '',
        classNames: '',
        isGroup: '',
        lessonICaseId: '',
        resourceCaseId: '',
        resourceGroupName: '',
        stuGroupList: '',
        stuNo: ''
      },
      groupStuNum: '',
      isShowGroupState: false,
      editState: false,
      ruleForm: {
        groupName: '',
        groupId: ''
      },
      rules: {
        groupName: [{ required: true, message: '请填写分组名称', trigger: 'blur' }],
        groupId: [{ required: true, message: '请选择分组角色', trigger: 'blur' }]
      },
      stuGroupList: [],
      groupIndex: 0,
      groupInd: 0,
      isShowStuState: false,
      currentStus: [],
      allStus: [],
      btnDisabled: false
    }
  },
  mounted () {
    this.trainingInteraction()
  },
  methods: {
    async trainingInteraction () {
      const res = await trainingInteraction({ resourceCaseId: this.resourceCaseId })
      if (res.code === '200') {
        this.cases = res.data
        if (this.cases.isGroup === '1') {
          this.groupShow()
        } else {
          this.groupAllocation()
        }
      } else {
        this.$message.error(res.message)
      }
    },
    async groupAllocation () {
      const res = await groupAllocation({ lessonICaseId: this.cases.lessonICaseId })
      if (res.code === '200') {
        this.allocates = res.data
        this.allocates.caseGroupList = JSON.parse(this.allocates.caseGroupList)
        this.allocates.stuInfoList = JSON.parse(this.allocates.stuInfoList)
        this.allStus = this.allocates.stuInfoList.map(item => ({
          classId: item.classId,
          stuId: item.stuId,
          headImgUrl: item.headImgUrl,
          stuName: item.stuName,
          isHeadman: '0',
          isCheck: false
        }))
        this.stuGroupList = this.allocates.caseGroupList.map(item => ({
          caseGroupId: item.caseGroupId,
          caseGroupName: item.caseGroupName,
          stuGroupList: []
        }))
      } else {
        this.$message.error(res.message)
      }
    },
    async groupShow () {
      const res = await groupShow({ lessonICaseId: this.cases.lessonICaseId })
      if (res.code === '200') {
        this.groups = res.data
        this.stuGroupList = this.groups.stuGroupList = JSON.parse(this.groups.stuGroupList)
      } else {
        this.$message.error(res.message)
      }
    },
    // 自动分组
    async autoGroup () {
      if (this.groupStuNum < 1) {
        this.$message.warning('请设置分组人数')
        return
      }
      const res = await autoGroup({
        groupStuNum: this.groupStuNum,
        lessonICaseId: this.cases.lessonICaseId
      })
      if (res.code === '200') {
        this.$message.success('自动分组成功!')
        this.groups = res.data
        this.groups.caseGroupList = JSON.parse(this.groups.caseGroupList)
        // 自动分组，待选学生isCheck=true
        this.allStus = this.allStus.map(item => ({
          classId: item.classId,
          stuId: item.stuId,
          headImgUrl: item.headImgUrl,
          stuName: item.stuName,
          isHeadman: '0',
          isCheck: true
        }))
        this.stuGroupList = this.groups.stuGroupList = JSON.parse(this.groups.stuGroupList)
      } else {
        this.$message.error(res.message)
      }
    },
    // 添加分组
    addGroup () {
      this.ruleForm = {
        groupName: '',
        groupId: ''
      }
      this.editState = false
      this.isShowGroupState = true
    },
    // 编辑分组
    editGroup (item, it, index, ind) {
      this.ruleForm = {
        groupName: it.caseStuGroupName,
        groupId: item.caseGroupId
      }
      this.groupIndex = index
      this.groupInd = ind
      this.editState = true
      this.isShowGroupState = true
    },
    // 删除分组
    deleteGroup (index, ind) {
      this.$confirm('是否确认删除该分组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.allStus.forEach(item => {
          this.stuGroupList[index].stuGroupList[ind].stuGroup.forEach((t, d) => {
            if (item.stuId === t.stuId) {
              item.isCheck = false
            }
          })
        })
        this.stuGroupList[index].stuGroupList.splice(ind, 1)
      })
    },
    // 选择成员
    addGroupStu (index, ind) {
      this.groupIndex = index
      this.groupInd = ind
      this.isShowStuState = true
    },
    handleSelectionChange (val) {
      this.currentStus = val
    },
    submitGroup (ruleForm) {
      this.$refs[ruleForm].validate(async valid => {
        if (valid) {
          if (this.editState) {
            this.stuGroupList[this.groupIndex].stuGroupList[this.groupInd].caseStuGroupName = this.ruleForm.groupName
          } else {
            this.stuGroupList.forEach(item => {
              if (item.caseGroupId === this.ruleForm.groupId) {
                item.stuGroupList.push({
                  caseStuGroupName: this.ruleForm.groupName,
                  stuGroup: []
                })
              }
            })
          }
          this.isShowGroupState = false
        } else {
          return false
        }
      })
    },
    submitStudent () {
      const list = this.currentStus.map(item => ({
        classId: item.classId,
        stuId: item.stuId,
        headImgUrl: item.headImgUrl,
        stuName: item.stuName,
        isHeadman: item.isHeadman
      }))
      this.stuGroupList[this.groupIndex].stuGroupList[this.groupInd].stuGroup = this.stuGroupList[this.groupIndex].stuGroupList[this.groupInd].stuGroup.concat(list)
      // 每组第一个默认组长
      this.stuGroupList[this.groupIndex].stuGroupList[this.groupInd].stuGroup[0].isHeadman = '1'
      // 设置已选
      this.allStus.forEach(item => {
        this.currentStus.forEach(it => {
          if (item.stuId === it.stuId) {
            item.isCheck = true
          }
        })
      })
      this.isShowStuState = false
    },
    // 设为组长
    handleSetStu (index, id, d) {
      const stuGroup = this.stuGroupList[index].stuGroupList[id].stuGroup.map((item, i) => ({
        classId: item.classId,
        stuId: item.stuId,
        headImgUrl: item.headImgUrl,
        stuName: item.stuName,
        isHeadman: i === d ? '1' : '0'
      })).sort(this.compare('isHeadman'))
      this.stuGroupList[index].stuGroupList[id].stuGroup = stuGroup
    },
    // 删除学生
    handleDeleteStu (index, id, d) {
      this.$confirm('是否将该学生移出该组?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        const stuId = this.stuGroupList[index].stuGroupList[id].stuGroup[d].stuId
        this.stuGroupList[index].stuGroupList[id].stuGroup.splice(d, 1)
        this.allStus.forEach(item => {
          if (item.stuId === stuId) {
            item.isCheck = false
          }
        })
      })
    },
    closeGroupBox () {
      this.isShowGroupState = false
    },
    closeStuBox () {
      this.isShowStuState = false
    },
    // 提交
    handleSubmit () {
      if (!this.allStus.some(item => item.isCheck)) {
        this.$message.warning('请设置学生分组')
        return
      }
      let confirmStr = '确认提交分组，开始实训?'
      if (this.allStus.some(item => !item.isCheck)) {
        confirmStr = '还有学生未分配小组，是否继续开始实训?'
      }
      this.$confirm(confirmStr, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.groupCommit()
      })
    },
    async groupCommit () {
      const res = await groupCommit({
        lessonICaseId: this.cases.lessonICaseId,
        stuGroupList: this.stuGroupList
      })
      if (res.code === '200') {
        this.$message.success('分组成功!')
        setTimeout(() => {
          this.$router.go(-1)
        }, 1000)
      } else {
        this.$message.error(res.message)
      }
    },
    compare (property) {
      return function (a, b) {
        var value1 = Number(a[property])
        var value2 = Number(b[property])
        // 降序排列
        return value2 - value1
      }
    }
  }
}
</script>
<style scoped lang="scss" rel="stylesheet/scss">
  .interaction-start {
    .container {
      display: flex;
      justify-content: space-between;
      .box-left {
        width: 460px;
        background: #fff;
        padding: 15px;
        .section {
          .sm-group{
            margin-top: 10px;
          }
          .train-info {
            color: #BBBBBB;
            font-size: 14px;
            margin-top: 10px;
          }
          .content {
            color: #BBBBBB;
            font-size: 14px;
            padding:20px 0;
            line-height: 1.2;
          }
          .card {
            border-radius: 20px;
            background: #f5f5f5;
            width: 455px;
            margin: 0 auto;
            .row {
              display: flex;
              align-items: center;
              justify-content: space-between;
            }
            .row-1{
              padding: 0 20px;
              line-height: 60px;
              border-bottom: 1px solid #D2D2D2;
            }
            .row-2{
              padding: 0 60px;
              line-height: 50px;
            }
          }
          .list-box {
            margin-top: 20px;
            ul {
              li {
                display: flex;
                justify-content: space-between;
                line-height: 60px;
                font-size: 14px;
                border-bottom: 1px solid #f5f5f5;
                padding: 0 10px;
                position: relative;
                cursor: pointer;
                i{
                  margin-left: 10px;
                }
                &:hover {
                  background: #f5f5f5;
                }
                .right-arrow {
                  position: absolute;
                  right: 10px;
                }
                .inter-man{
                  display: flex;
                  white-space: nowrap;
                  .el-input{
                    width: 140px;
                    margin-right: 10px;
                  }
                }
              }
            }
          }
        }
      }
      .box-right {
        width: 720px;
        min-height: 100%;
        background: #fff;
        padding: 15px;
        box-sizing: border-box;
        .title {
          font-size: 14px;
          font-weight: bold;
          position: relative;
          display: flex;
          align-items: center;
          justify-content: space-between;
          .tab {
            display: flex;
            .tab-item {
              width: 85px;
              line-height: 40px;
              border: 1px solid #D9D9D9;
              text-align: center;
              font-weight: initial;
              cursor: pointer;
              &.active {
                border: 1px solid #828282;
              }
            }
          }
          .time {
            font-size: 14px;
            color: #828282;
            position: absolute;
            right: 0;
            font-weight: normal;
          }
        }
        .content {
          color:#BBBBBB;
          font-size: 14px;
          padding:20px 0;
          line-height: 1.2;
        }
        .media-box {
          padding: 15px 0;
          .video {
            width: 100%;
          }
        }
        .file-box {
          line-height: 40px;
          display: flex;
          justify-content: space-between;
          border-bottom: 1px solid #f5f5f5;
          font-size: 14px;
          font-weight: bold;
          a {
            color: #009cf6;
            font-weight: normal;
          }
        }
        .fill-box {
          .fill-title {
            font-size: 14px;
          }
          textarea {
            width: 100%;
            margin-top: 20px;
          }
        }
        .report-box {
          li {
            line-height: 70px;
            position: relative;
            .right-arrow {
              position: absolute;
              right: 0;
            }
            textarea {
              width: 100%;
              margin-top: 20px;
            }
          }
        }
        .wait-btn, .submit-btn {
          width: 100%;
          line-height: 40px;
          border-radius: 10px;
          background: #BBBBBB;
          color: #fff;
          text-align: center;
          margin-top: 30px;
          cursor: pointer;
        }
      }
    }
  }
  .group-tips{
    display: flex;
    justify-content: space-between;
    line-height: 28px;
    margin: 10px 0;
  }
  .group-tip{
    font-size: 12px;
  }
  .group-con{
    display: flex;
    flex-wrap: wrap;
  }
  .group-cont{
    width: 168px;
    padding: 0 10px 10px 10px;
    margin-right: 6px;
    margin-bottom: 15px;
    border: 1px solid #ddd;
    border-radius: 10px;
  }
  .group-cont:nth-child(4n) {
    margin-right: 0;
  }
  .group-man{
    display: flex;
    line-height: 57px;
    justify-content: center;
    align-items: center;
    font-size: 12px;
  }
  .group-logo{
    width: 30px;
    height: 30px;
  }
  .group-stuName{
    padding: 0 5px;
    white-space: nowrap;
    overflow: hidden;
    -ms-text-overflow: ellipsis;
    text-overflow: ellipsis;
  }
  .group-doBox{
    display: flex;
    justify-content: center;
  }
  .inter-btn{
    width: 100%;
    margin: 15px auto;
  }
</style>
